<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>this绑定</title>
</head>
<body>
<script>
    var name = 'window'

    var person1 = {
        name: 'person1',
        show1: function () {
            console.log(this.name)
        },
        show2: () => console.log(this.name),
        show3: function () {
            return function () {
                console.log(this.name)
            }
        },
        show4: function () {
            return () => console.log(this.name)
        }
    }
    var person2 = {name: 'person2'}

    person1.show1()
    person1.show1.call(person2)

    person1.show2()
    person1.show2.call(person2)

    person1.show3()()
    person1.show3().call(person2)
    person1.show3.call(person2)()

    person1.show4()()
    person1.show4().call(person2)
    person1.show4.call(person2)()

    console.log("======================================")

    var obj = {
        say: function () {
            function _say() {
                console.log(this);
            }
            console.log(obj);
            return _say.bind(obj);
        }()
    };
    obj.say();
    // ---------------this 软绑定 --------------
    if(!Function.prototype.softBind) {
        Function.prototype.softBind = function (obj) {
            var fn = this;
            // 捕获所有的curried参数
            var curried = [].slice.call(arguments,1);
            var bound = function () {
                return fn.apply(
                    (!this || this === (window || global)) ?
                        obj : this,
                    curried.concat.apply(curried,arguments)
                );
            };
            bound.prototype = Object.create(fn.prototype);
            return bound;
        };
    }
    var name = '王思聪';
    var theshy = {name:'the shy'};
    var jacky = {name:'jackylove'};
    function foo() {
        console.log(this.name)
    }
    foo.call(theshy);  // the shy
    theshy.foo = foo;
    theshy.foo(); // the shy
    (jacky.foo = theshy.foo)(); // '王思聪'
    jacky.foo(); // 'jackylove'
    setTimeout(theshy.foo, 0); // '王思聪'
    var foobind = foo.bind(jacky);
    foobind.call(theshy); //
    theshy.foobind = foobind;
    theshy.foobind(); //
    new foobind(); //
</script>
</body>
</html>
